﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Xml;
using Darren.Common.Helper;

namespace OAuth
{

    /// <summary>
    /// urls
    /// </summary>
    internal class Urls
    {
        internal const string RequestToken = "http://api.t.163.com/oauth/request_token";

        internal const string Authenticate = "http://api.t.163.com/oauth/authenticate";

        internal const string Authorize = "http://api.t.163.com/oauth/authorize";

        internal const string AccessToken = "http://api.t.163.com/oauth/access_token";

        internal const string PublicTimeLine = "http://api.t.163.com/statuses/public_timeline.json";

        internal const string HomeTimeLine = "http://api.t.163.com/statuses/home_timeline.json";

        internal const string Mentions = "http://api.t.163.com/statuses/mentions.json";

        internal const string UserTimeLine = "http://api.t.163.com/statuses/user_timeline.json";

        internal const string RetweetsOfMe = "http://api.t.163.com/statuses/retweets_of_me.json";

        internal const string CommentsByMe = "http://api.t.163.com/statuses/comments_by_me.json";

        internal const string CommentsToMe = "http://api.t.163.com/statuses/comments_to_me.json";

        internal const string UpdateStatues = "http://api.t.163.com/statuses/update.json";

        internal const string Reply = "http://api.t.163.com/statuses/reply.json";

        internal const string Retweet = "http://api.t.163.com/statuses/retweet/{0}.json";

        internal const string Show = "http://api.t.163.com/statuses/show/{0}.json";

        internal const string Comments = "http://api.t.163.com/statuses/comments/{0}.json";

        internal const string Destroy = "http://api.t.163.com/statuses/destroy/{0}.json";

        internal const string RetweetedBy = "http://api.t.163.com/statuses/{0}/retweeted_by.json";

        internal const string Upload = "http://api.t.163.com/statuses/upload.json";

        internal const string UserShow = "http://api.t.163.com/users/show.json";

        //                               http://api.t.163.com/statuses/friends.json
        internal const string Friends = "http://api.t.163.com/statuses/friends.json";

        internal const string Followers = "http://api.t.163.com/statuses/followers.json";

        internal const string Suggestions = "http://api.t.163.com/users/suggestions.json";

        internal const string SuggestionsIFollowers = "http://api.t.163.com/users/suggestions_i_followers.json";

        internal const string FriendshipCreate = "http://api.t.163.com/friendships/create.json";

        internal const string FriendshipShow = "http://api.t.163.com/friendships/show.json";

        internal const string FriendshipDestroy = "http://api.t.163.com/friendships/destroy.json";

        internal const string TopRetweets = "http://api.t.163.com/statuses/topRetweets.json";

        internal const string TrendsRecommended = "http://api.t.163.com/trends/recommended.json";

        internal const string DirectMessages = "http://api.t.163.com/direct_messages.json";

        internal const string DirectMessagesSent = "http://api.t.163.com/direct_messages/sent.json";

        internal const string DirectMessagesNew = "http://api.t.163.com/direct_messages/new.json";

        internal const string DirectMessageDestroy = "http://api.t.163.com/direct_messages/destroy/{0}.json";

        internal const string Activate = "http://api.t.163.com/account/activate.json";

        internal const string UpdateProfile = "http://api.t.163.com/account/update_profile.json";

        internal const string UpdateProfielImage = "http://api.t.163.com/account/update_profile_image.json";

        internal const string RateLimitStatus = "http://api.t.163.com/account/rate_limit_status.json";

        internal const string Favorites = "http://api.t.163.com/favorites/{0}.json";

        internal const string FavoritesCreate = "http://api.t.163.com/favorites/create/{0}.json";

        internal const string FavoritesDestroy = "http://api.t.163.com/favorites/destroy/{0}.json";

        internal const string BlocksCreate = "http://api.t.163.com/blocks/create.json";

        internal const string BlocksExists = "http://api.t.163.com/blocks/exists.json";

        internal const string BlocksBlocking = "http://api.t.163.com/blocks/blocking.json";

        internal const string BlockingIds = "http://api.t.163.com/blocks/blocking/ids.json";

        internal const string BlocksDestroy = "http://api.t.163.com/blocks/destroy.json";

        internal const string Venues = "http://api.t.163.com/location/venues.json";

        internal const string LocationTimeLine = "http://api.t.163.com/statuses/location_timeline.json";

        internal const string Search = "http://api.t.163.com/search.json";

        internal const string StatuesSearch = "http://api.t.163.com/statuses/search.json";

        internal const string UserSearch = "http://api.t.163.com/users/search.json";

        internal const string VerifyCredential = "http://api.t.163.com/account/verify_credentials.json";

        internal const string Retweets = "http://api.t.163.com/statuses/retweets/{0}.json";

        internal const string Letest = "http://api.t.163.com/reminds/message/latest.json";
    }

    public class NetEasyOAuth : OAuthBase
    {
        public static string AppKey
        {
            get { return ConfigHelper.GetConfigString("NetEasy_AppKey"); }
        }
        public static string AppSecret
        {
            get { return ConfigHelper.GetConfigString("NetEasy_AppSecret"); }
        }
        public static string CallBackURL
        {
            get { return ConfigHelper.GetConfigString("NetEasy_CallBackURL"); }
        }

        public NetEasyOAuth()
        {
            this.app_id = NetEasyOAuth.AppKey;
            this.app_key = NetEasyOAuth.AppSecret;
        }
        public NetEasyOAuth(string _appid, string _appkey)
            : base(_appid, _appkey)
        {

        }
        public string Login(out AccessToken token, string callbackUrl)
        {
            string qzoneoauth_request_token_url = Urls.RequestToken;
            if (string.IsNullOrEmpty(callbackUrl))
                throw new ArgumentNullException("请提供Oauth_callback属性");


            string result = GenResponse(qzoneoauth_request_token_url);

            NameValueCollection nvc = HttpUtility.ParseQueryString(result);
            if (nvc["error_code"] != null)
            {
                //throw new Exception(nvc["error_code"] + ":" + GenErrorMessage(nvc["error_code"]));
            }

            token = new AccessToken();
            token.Token = nvc["oauth_token"];
            token.TokenSecret = nvc["oauth_token_secret"];
            return string.Format("{0}?oauth_consumer_key={3}&oauth_token={1}&oauth_callback={2}", Urls.Authenticate, token.Token, callbackUrl, this.app_id);
        }
        /// <summary>
        /// 获取授权参数，如openid
        /// </summary>
        /// <param name="oauth_token">未授权的token</param>
        /// <returns></returns>
        public AccessToken GetAccessToken()
        {
            checkToken();
            string url = string.Format("{0}", Urls.AccessToken);
            string result = GenResponse(url);
            NameValueCollection nvc = HttpUtility.ParseQueryString(result);
            if (nvc["error_code"] != null)
            {
                //throw new Exception(nvc["error_code"] + ":" + GenErrorMessage(nvc["error_code"]));
            }
            return new AccessToken(nvc["oauth_token"], nvc["oauth_token_secret"], nvc["openid"]);
        }
        public MemberInfo GetUserInfo()
        {
            checkToken();
            string url = Urls.UserShow;
            string result = GenResponse(url);

            XmlDocument doc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(result, "root");

            string displayName = doc.SelectSingleNode("/root/name").InnerXml;
            string middleFace = doc.SelectSingleNode("/root/profile_image_url").InnerXml;
            string memderid = doc.SelectSingleNode("/root/email").InnerXml;

            return new MemberInfo(displayName, memderid, middleFace);
        }
        public string GetFriends(string name)
        {
            checkToken();
            string url = "";
            if (string.IsNullOrEmpty(name))
            {
                url = Urls.Friends;
            }
            else
            {
                url = Urls.Friends + "?screen_name=" + name;
            }
            
            string result = GenResponse(url);

            return result;
        }
        public string UpdateStatus(string content)
        {
            checkToken();
            content = Microsoft.JScript.GlobalObject.encodeURIComponent(content);
            //一定要用POST方法
            string url = string.Format("{1}?status={0}", content, Urls.UpdateStatues);
            //为了支持中文，一定要通过 Microsoft.JScript.GlobalObject.encodeURIComponent编码，不能用HttpUtility.UrlEncode        


            return GenResponse(url, "POST");

        }
        public string FriendshipCreate(string name)
        {
            checkToken();
            string url = "";
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            else
            {
                url = Urls.FriendshipCreate + "?screen_name=" + name;
            }

            string result = GenResponse(url,"POST");

            return result;
        }
    }
}